import React, { useState, useCallback, useEffect, useRef } from "react";
import PhotoSphere from "./components/PhotoSphere";

// 定义全景图数据类型
interface PanoramaItem {
  id: string;
  src: string;
  thumbnail: string;
  title: string;
  // 背景音乐 URL
  music: string;
}

type Props = {
  height?: string;
  width?: string;
};

const PhotoSphereView: React.FC<Props> = ({
  height = "100%",
  width = "100%",
}) => {
  // 房间全景图数据列表
  const panoramaList: PanoramaItem[] = [
    {
      id: "1",
      src: "/panoramic/demo1.jpg",
      thumbnail: "/panoramic/demo1.jpg",
      title: "荒漠",
      music: "https://cdn.pixabay.com/download/audio/2025/08/13/audio_de73eb330d.mp3?filename=hopeful-corporate-uplifting-and-inspiring-389391.mp3",
    },
    {
      id: "2",
      src: "/panoramic/demo2.jpg",
      thumbnail: "/panoramic/demo2.jpg",
      title: "城市",
      music: "https://cdn.pixabay.com/download/audio/2025/08/11/audio_e44e8ec9fd.mp3?filename=motivation-motivational-background-music-388288.mp3",
    },
    {
      id: "3",
      src: "/panoramic/demo3.jpg",
      thumbnail: "/panoramic/demo3.jpg",
      title: "乡村",
      music: "https://cdn.pixabay.com/download/audio/2025/08/03/audio_ab19872d5b.mp3?filename=wild-kingdom-theme-384193.mp3",
    },
    {
      id: "4",
      src: "/panoramic/demo4.jpeg",
      thumbnail: "/panoramic/demo4.jpeg",
      title: "荒漠",
      music: "https://cdn.pixabay.com/download/audio/2025/08/03/audio_3564935fb0.mp3?filename=memories-of-nature-384195.mp3",
    },
  ];

  // 当前选中的全景图索引
  const [currentIndex, setCurrentIndex] = useState(0);

  // 获取当前全景图
  const currentPanorama = panoramaList[currentIndex];

  // 用户是否已与全景交互（用于允许自动播放音乐）
  const [hasUserInteracted, setHasUserInteracted] = useState(false);

  // 切换全景图函数
  const handlePanoramaChange = useCallback((index: number, triggerInteraction = true) => {
    // 如果是通过缩略图点击并且还没交互，先标记交互以便允许播放
    if (triggerInteraction && !hasUserInteracted) {
      setHasUserInteracted(true);
    }
    setCurrentIndex(index);
  }, [hasUserInteracted]);

  // 音频播放管理
  const audioRef = useRef<HTMLAudioElement | null>(null);

  useEffect(() => {
    const musicUrl = currentPanorama.music;
    if (!musicUrl) return;

    if (!audioRef.current) {
      audioRef.current = new Audio(musicUrl);
      audioRef.current.loop = true;
    } else {
      audioRef.current.src = musicUrl;
    }

    // 仅在用户已交互后尝试播放
    if (hasUserInteracted) {
      audioRef.current
        .play()
        .catch(() => {
          // 忽略播放失败（浏览器自动播放策略），可在 UI 中提供播放按钮
        });
    }

    return () => {
      if (audioRef.current) {
        audioRef.current.pause();
      }
    };
  }, [currentPanorama, hasUserInteracted]);

  return (
    <div className="relative" style={{ width, height }}>
      {/* 全景图展示组件 */}
      <PhotoSphere
        src={currentPanorama.src}
        height={height}
        width={width}
        onStartInteraction={() => setHasUserInteracted(true)}
      />

      {/* 底部房间导航栏 */}
      <div className="absolute bottom-8 left-1/2 transform -translate-x-1/2 flex gap-2 px-3 py-2 bg-black/20 z-[1000] overflow-x-auto w-full justify-center">
    {panoramaList.map((panorama, index) => (
          <div
            key={panorama.id}
      onClick={() => handlePanoramaChange(index, true)}
            className="flex flex-col items-center min-w-[80px] cursor-pointer"
          >
            <div className={`w-20 h-20 overflow-hidden border-[2px] relative ${currentIndex === index
                ? 'border-[#e6b328]'
                : 'border-white/80'
              }`}>
              <img
                src={panorama.thumbnail}
                alt={panorama.title}
                className="w-full h-full object-cover"
              />
              {currentIndex === index && (
                <div className="absolute inset-0" />
              )}
              <span className="absolute bottom-0 left-0 right-0 text-xs text-white text-center bg-black/50 px-1 py-0.5 transition-all duration-300 whitespace-nowrap">
                {panorama.title}
              </span>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
};

export default PhotoSphereView;
